from typing import Union, Annotated

from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm.session import Session

from server.controller.login import user_login
from server.etc.database import create_db
from server.schemas.login import (
    UserLogin, LoginResponse, LoginUsernameOrPasswordError,
    LoginUsernameIsNotActive, LoginPasswordValidateError, SuperuserLoginResponse
)

router = APIRouter()


def determine_response_model(result: dict):
    if result.get("is_superuser"):
        return SuperuserLoginResponse(**result)
    return LoginResponse(**result)


@router.post(
    "",
    response_model=Annotated[
        Union[LoginResponse, SuperuserLoginResponse],
        determine_response_model
    ],
    responses={
        400: {"model": LoginUsernameOrPasswordError,"description":"用户名或密码错误"},
        401: {"model": LoginUsernameIsNotActive, "description":"用户未激活错误"},
        402: {"model": LoginPasswordValidateError, "description":"用户密码复杂度不满足"},
    }
)
async def login(request: Request, loginDate:UserLogin, db: Session = Depends(create_db)):
    """
    用户登录
    """
    result = user_login(request, loginDate, db)
    return result